package org.come.Jpanel;

import com.tool.btn.TitlelBtn;
import com.tool.image.ImageMixDeal;
import com.tool.tab.Main;
import com.tool.tab.TabJFrame;
import com.tool.tcpimg.UIUtils;
import org.apache.commons.lang.StringUtils;
import org.come.bean.LoginResult;
import org.come.control.TestMain;
import org.come.socket.GameClient;
import org.come.until.CutButtonImage;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.RoundRectangle2D;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class CustomTitleBarUI extends JPanel {
    private JLabel titleLabel;
    private TitlelBtn b1, b2;
    private TitlelBtn c1, c2, c3, c4;
    private List<TitlelBtn> titlelBtns;
    private String title;
    private Image myimage;
    private Integer index = 0;
    private JFrame jFrame;
    private int first_x;
    private int first_y;
    private static ImageIcon sharedImage = null;
    private static final Object imageLock = new Object();

    private static final String[] BG_IMAGES = {
            "resource/NewRoleUi/36角色/最新特效/intibg1.png",
            "resource/NewRoleUi/36角色/最新特效/intibg2.png",
            "resource/NewRoleUi/36角色/最新特效/intibg3.png",
            "resource/NewRoleUi/36角色/最新特效/intibg4.png"
    };
    private ImageIcon image; // 每个实例使用自己的随机背景图

    private ImageIcon getBackgroundImage() {
        // 每个实例使用自己的随机背景图而不是共享的
        return image;
    }

    private JLabel jd;
    private int jdNum = 0;
    public static Boolean isShow = true;

    public CustomTitleBarUI(JFrame frame) {


        this.jFrame = frame;
        titlelBtns = new ArrayList<>();
        myimage = CutButtonImage.getImage("img/icon/ico.png", 16, 16).getImage();
        // 每次实例化都重新随机背景图
        this.image = CutButtonImage.getImage(
                BG_IMAGES[new Random().nextInt(BG_IMAGES.length)], 1016, 705
        );
        setPreferredSize(new Dimension(frame.getWidth(), 768));

        this.setOpaque(true);
        this.setForeground(Color.red);
        titleLabel = new JLabel(frame.getTitle());
        titleLabel.setOpaque(false);
        add(titleLabel);
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); // 设置鼠标样式为手型

        b1 = new TitlelBtn("inkImg/background/titleBtn1.png", 1, "", 98);
        b1.setBounds(5, 33, 12, 16);
        this.add(b1);


        c1 = new TitlelBtn("inkImg/background/title-3.png", 1, "", 99, jFrame);
        c1.setBounds(5, 33, 17, 17);
        this.add(c1);
        c2 = new TitlelBtn("inkImg/background/title-4.png", 1, "", 97);
        c2.setBounds(5, 33, 17, 17);
        this.add(c2);
        c3 = new TitlelBtn("inkImg/background/title-5.png", 1, "", 96);
        c3.setBounds(5, 33, 17, 17);
        this.add(c3);
        c4 = new TitlelBtn("inkImg/background/title-6.png", 1, "", 95);
        c4.setBounds(5, 33, 17, 17);
        this.add(c4);

        addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {


            }

            @Override
            public void mousePressed(MouseEvent e) {
                // 使用屏幕绝对坐标，避免多窗口时的鼠标偏移问题
                first_x = e.getXOnScreen() - frame.getX();
                first_y = e.getYOnScreen() - frame.getY();
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }
        });

        addMouseMotionListener(new MouseMotionListener() {
            @Override
            public void mouseMoved(final MouseEvent e) {
//
            }


            @Override
            public void mouseDragged(final MouseEvent e) {
                // 修复多窗口鼠标偏移问题
                final int x = e.getXOnScreen() - first_x;
                final int y = e.getYOnScreen() - first_y;
                // 使用绝对坐标设置窗口位置，避免多窗口时的鼠标偏移问题
                frame.setLocation(x, y);
//                Main.lastX = -1;
//                Main.lastY = -1;
            }
        });

        jd = new JLabel();
        jd.setIcon(new ImageIcon("resource/NewRoleUi/36角色/最新特效/jd.png"));
        jd.setBounds(260, 675, 0, 50);
        jd.setOpaque(false);
        this.add(jd);
//        this.setOpaque(false);
//        this.setBackground(new Color(0, 0, 0, 1));
    }

    public TitlelBtn refreshRoles() {
        TabJFrame jFrame = Main.tabJFrame;

        // 清理旧的按钮资源
        for (TitlelBtn titlelBtn : titlelBtns) {
            if (titlelBtn.getDelete() != null) {
                this.remove(titlelBtn.getDelete());
            }
            this.remove(titlelBtn);
        }
        titlelBtns.clear();

        final int[] j = {0};
        AtomicInteger i = new AtomicInteger();
        jFrame.games.forEach((k, v) -> {
//                    LoginResult loginResult = jFrame.roles.get(k);
                    TitlelBtn delBtn = new TitlelBtn("inkImg/background/title-7.png", 1, "", 100 + k);
                    TitlelBtn titlelBtn = new TitlelBtn("inkImg/background/titleBtn2.png", 1, "", k, true, delBtn) {
                        ImageIcon head = null;

                        @Override
                        protected void paintComponent(Graphics g) {
                            super.paintComponent(g);
                            g.setFont(UIUtils.TEXT_FONT);
                            LoginResult loginResult = Main.tabJFrame.roles.get(this.getCaozuo());
                            if (loginResult != null) {
                                // 只在需要时加载头像
                                if (head == null) {
                                    try {
                                        head = CutButtonImage.getImage("img/head/s" + loginResult.getSpecies_id().toString() + ".png", 18, 18);
                                    } catch (Exception e) {
                                        // 忽略异常，使用默认图像
                                    }
                                }
                                if (head != null)
                                    g.drawImage(head.getImage(), 5, 3, this);
                                g.setColor(Color.BLACK);
                                g.drawString(loginResult.getRolename(), 30, 16);
                                if (Main.tabJFrame.getShouId() == k)
                                    title = "大话西游经典版 $Revision: - " + loginResult.getBT() + " - " + loginResult.getRolename() + " (ID: " + loginResult.getRole_id().toString() + ")";
//                                else
//                                    title = "大话西游2经典版 ";


                            } else {
                                g.drawImage(myimage, 5, 3, this);
                                g.setColor(Color.BLACK);
                                g.drawString("大话西游经典版", 30, 16);
                                title = "大话西游经典版 ";
                            }

                        }

                        // 添加资源清理方法
                        public void cleanup() {
                            if (head != null) {
                                head.getImage().flush();
                                head = null;
                            }
                        }
                    };
                    titlelBtn.setDelete(delBtn);
                    titlelBtn.getDelete().setBounds(175 + j[0] * 275, 23, 13, 39);
                    if (j[0] == index) {
                        titlelBtn.btnchange(1);
                    } else {
                        titlelBtn.setBounds(20 + j[0] * 175, 35, 172, 23);
                    }
                    this.add(titlelBtn.getDelete());
                    this.add(titlelBtn);
                    titlelBtns.add(titlelBtn);
                    j[0]++;
                    c1.setBounds(20 + titlelBtns.size() * 175, 33, 17, 17);
                    i.addAndGet(1);
                }
        );


        showBtnPath();

        return titlelBtns.size() == 0 ? null : titlelBtns.get(titlelBtns.size() - 1);
    }

    public void changeSelect(int index) {
        for (int i = 0; i < titlelBtns.size(); i++) {
            if (titlelBtns.get(i).getCaozuo() == index) {
                titlelBtns.get(i).btnchange(1);
                titlelBtns.get(i).setGl(true);
                titlelBtns.get(i).setBounds(20 + i * 175, 30, 172, 23);
            } else {
                titlelBtns.get(i).setBounds(20 + i * 175, 31, 172, 23);
                titlelBtns.get(i).btnchange(0);
                titlelBtns.get(i).setGl(false);
            }
            titlelBtns.get(i).validate();
            titlelBtns.get(i).getDelete().setBounds(20 + i * 175, 31, 17, 17);
        }
        this.repaint();
    }

    public void showBtnPath() {
        try {
            // 只有当按钮列表不为空时才更新按钮位置
            if (titlelBtns != null && !titlelBtns.isEmpty()) {
                b1.setBounds(5, 33, 12, 16);
                c2.setBounds(getWidth() - 25, 7, 17, 17);
                c3.setBounds(getWidth() - 45, 5, 17, 17);
                c4.setBounds(getWidth() - 65, 3, 17, 17);
                c1.setBounds(20 + titlelBtns.size() * 175, 33, 17, 17);
                for (int i = 0; i < titlelBtns.size(); i++) {
                    if (i == index) {
                        titlelBtns.get(i).btnchange(1);
                        titlelBtns.get(i).setBounds(20 + i * 175, 30, 172, 23);
                    } else
                        titlelBtns.get(i).setBounds(20 + i * 175, 31, 172, 23);
                    if (titlelBtns.get(i).getDelete() == null) continue;
                    titlelBtns.get(i).getDelete().setBounds(175 + i * 175, 23, 13, 39);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        // 只在窗口尺寸发生变化时调用showBtnPath，避免重复布局计算导致闪烁
        // 使用一个标志来跟踪是否需要更新按钮位置
        if (getWidth() > 0 && getHeight() > 0) {
            showBtnPath();
        }

        Graphics2D g2d = (Graphics2D) g;
        g2d.setFont(UIUtils.TEXT_FONT21);
        Color color = new Color(92, 122, 155);
        Color color1 = new Color(113, 154, 194);
        GradientPaint gradient = new GradientPaint(0, 0, color, 0, getHeight() - 1, color1);
        g2d.setPaint(gradient);
        RoundRectangle2D roundedRect = new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(), 10, 10);

        if (Main.tabJFrame.start && jdNum <= 520 && System.currentTimeMillis() % 5 == 0l) {
            jd.setBounds(260, 675, jdNum, 50);
            jdNum += 10;
        } else if (jdNum >= 520) {
            Main.tabJFrame.start = false;
            jd.setVisible(false);
        }


        g2d = (Graphics2D) g;
        g2d.fill(roundedRect);
        g2d.setComposite((Composite) AlphaComposite.getInstance(3, 0.03f));
        g2d.fill(roundedRect);
        g2d.fill(roundedRect);

        g2d.setComposite((Composite) AlphaComposite.getInstance(3, 0.8f));
        g2d.setColor(color);
        g2d.fillRect(0, 40, getWidth(), 35);
        g2d.setColor(Color.BLACK);
        g2d.fillRect(6, 52, getWidth() - 12, 1);
        g2d.setColor(color);
        roundedRect = new RoundRectangle2D.Float(0, 53, getWidth(), 15, 0, 0);
        g2d.fill(roundedRect);
        g2d.setColor(new Color(238, 238, 238));
        roundedRect = new RoundRectangle2D.Float(5, 53, getWidth() - 10, 20, 5, 5);
        g2d.fill(roundedRect);
        g2d.setComposite((Composite) AlphaComposite.getInstance(3, 1f));
        g2d.setColor(Color.BLACK);
        if (StringUtils.isNotBlank(title)) {
            g2d.setFont(UIUtils.TEXT_FONT);
            g2d.drawString(title, 30, 20);
//            g2d.drawString("官网:xy2.163.com", ScrenceUntil.Screen_x - 160, 20);
//            g2d.drawString("官网:xy2.163.com", ScrenceUntil.Screen_x - 160, 20);
//            g2d.setColor(Color.BLACK);
//            g2d.fillRect(ScrenceUntil.Screen_x - 131, 23, 68, 1);
        }
        // 在title-6.png左边20像素处绘制官网链接文字
        if (c4 != null) {
            g2d.setFont(UIUtils.TEXT_FONT);
            int textX = c4.getX() - 120;
            int textY = 20;

            // 添加凸陷感（绘制阴影，左上角）
            g2d.setColor(Color.GRAY);
            g2d.drawString("官网:xy2.163.com", textX - 1, textY - 1);
            // 绘制主要文字
            g2d.setColor(Color.BLACK);
            g2d.drawString("官网:xy2.163.com", textX, textY);

            // 仅为"xy2.163.com"添加下划线
            FontMetrics fm = g2d.getFontMetrics();
            int underlineStartX = textX + fm.stringWidth("官网:");
            int underlineY = textY + 2;
            int underlineWidth = fm.stringWidth("xy2.163.com");
            g2d.drawLine(underlineStartX, underlineY, underlineStartX + underlineWidth, underlineY);
        }
        g2d.drawImage(myimage, 5, 7, null);
        if (isShow) {
            ImageIcon bgImage = getBackgroundImage();
            if (bgImage != null) {
                // 调整图片绘制的位置和尺寸，使其适应界面
                g.drawImage(bgImage.getImage(), 5, 60, getWidth() - 10, getHeight() - 65, null);
            }
        }

//        setPreferredSize(new Dimension(Main.tabJFrame.getWidth(), Main.tabJFrame.getHeight()));
//        repaint();
    }

    public void updateTitle(String newTitle) {
        titleLabel.setText(newTitle);
    }

    public void initJD() {

        jdNum = 0;
        jd.setBounds(260, 675, 0, 50);
        jd.setVisible(true);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Custom Title Bar UI Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
//        frame.setUndecorated(true);
        CustomTitleBarUI customTitleBarUI = new CustomTitleBarUI(frame);
        customTitleBarUI.setOpaque(false);
        frame.add(customTitleBarUI, BorderLayout.NORTH);

        frame.setVisible(true);
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setTitle() {
//        GameClient gameClient = SendMessageUntil.getGameClient();
        setTitle("大话西游经典版 $Revision: - " + GameClient.BT + " - " + ImageMixDeal.userimg.getRoleShow().getRolename() + " (ID: " + ImageMixDeal.userimg.getRoleShow().getRole_id() + ")");
        TestMain.gameJframe.setTitle("大话西游经典版 $Revision: - " + GameClient.BT + " - " + ImageMixDeal.userimg.getRoleShow().getRolename() + " (ID: " + ImageMixDeal.userimg.getRoleShow().getRole_id() + ")");
//        } else {
//            setTitle("大话西游2经典版");
////            TestMain.gameJframe.setTitle("大话西游2经典版");
//        }

    }

    public Integer getIndex() {
        return index;
    }

    public void setIndex(Integer index) {
        this.index = index;
    }


    public void removeMenus(Integer i) {
        if (i >= 0 && i < titlelBtns.size()) {
            TitlelBtn titlelBtn = this.titlelBtns.get(i);
            // 清理资源
            if (titlelBtn instanceof TitlelBtnWithCleanup) {
                ((TitlelBtnWithCleanup) titlelBtn).cleanup();
            }
            if (titlelBtn.getDelete() != null) {
                this.remove(titlelBtn.getDelete());
            }
            this.remove(titlelBtn);
            titlelBtns.remove(i);
        }
        showBtnPath();
    }

    public TitlelBtn getC1() {
        return c1;
    }

    public void setC1(TitlelBtn c1) {
        this.c1 = c1;
    }

    public List<TitlelBtn> getTitlelBtns() {
        return titlelBtns;
    }

    public void setTitlelBtns(List<TitlelBtn> titlelBtns) {
        this.titlelBtns = titlelBtns;
    }

    // 添加清理所有资源的方法
    public void cleanup() {
        // 清理所有TitlelBtn资源
        for (TitlelBtn titlelBtn : titlelBtns) {
            if (titlelBtn instanceof TitlelBtnWithCleanup) {
                ((TitlelBtnWithCleanup) titlelBtn).cleanup();
            }
        }
        titlelBtns.clear();

        // 清理其他资源
        if (sharedImage != null) {
            sharedImage.getImage().flush();
            sharedImage = null;
        }

        // 清理实例的背景图资源
        if (image != null) {
            image.getImage().flush();
            image = null;
        }

        if (myimage != null) {
            myimage.flush();
            myimage = null;
        }
    }

    // 定义一个带清理功能的TitlelBtn接口
    private interface TitlelBtnWithCleanup {
        void cleanup();
    }
}
